package Model;

import View.Editor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.Socket;
import javax.swing.JOptionPane;

/**
 *
 * @author kiko
 */
public class ClientMessageReceiver extends Thread {

    private Socket connection;
    private String message;
    private BufferedReader in;
    private DataOutputStream out;

    public ClientMessageReceiver(Socket connection) {
        this.connection = connection;
        try {
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            out = new DataOutputStream(connection.getOutputStream());
        } catch (IOException e) {
            System.out.println("Erro ao tentar instanciar CMessageReceiver");
        }
    }
    
    @Override
    public void run() {
        try {
            interpretMessage(in, out);
        } catch (IOException e) {
            System.out.println("Erro ao tentar interpretar mensagem do servidor");
        }
    }
    
    private void interpretMessage(BufferedReader in, DataOutputStream out) throws IOException {
        while (true) {
            message = in.readLine();
            String auxMessage = message.split(":")[0];
            System.out.println("Mensagem " + auxMessage + " recebida de: " + connection.getInetAddress().toString());
            switch (auxMessage) {
                case "PDEN"://Permission denied
                    JOptionPane.showMessageDialog(null, "Permissão negada.\nO arquivo já está sendo usado. Tente novamente mais tarde");
                    break;
                case "PGRA"://Permission granted
                    String keyWord = message.split(":")[1];
                    String file = message.split(":")[2];
                    Editor editor = new Editor(file, keyWord, connection);
                    editor.setVisible(true);
                    BufferedWriter bw = new BufferedWriter(new FileWriter("permissions" + File.separator + file));
                    bw.write(keyWord);
                    bw.close();
                    break;
                case "FILE":
                    Socket sock = new Socket(connection.getInetAddress(), 50300);
                    ObjectInputStream inputArc = new ObjectInputStream(new BufferedInputStream(sock.getInputStream()));
                    String fileName = inputArc.readUTF();
                    long size = inputArc.readLong();
                    System.out.println("Processando arquivo " + fileName + " - " + size + " bytes.");
                    BufferedOutputStream saveArq = new BufferedOutputStream(new FileOutputStream("files" + File.separator + fileName));
                    byte[] buf = new byte[4096];
                    int temp = 0;
                    while (true) {
                        int len;
                        if (size - temp > 0) {
                            len = inputArc.read(buf);
                        } else {
                            saveArq.close();
                            break;
                        }
                        temp = temp + len;
                        saveArq.write(buf, 0, len);
                        saveArq.flush();
                    }
                    JOptionPane.showMessageDialog(null, "Arquivo recebido com sucesso");
                    sock.close();
                    break;
            }
        }
    }
}
